//
//  ViewController.swift
//  CoreDataSwift
//
//  Created by liuxiang on 2018/1/9.
//  Copyright © 2018年 liuxiang. All rights reserved.
//

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
    
    var fetchResultsController: NSFetchedResultsController<NSFetchRequestResult>!
    lazy var tableView: UITableView = {
        var tableView = UITableView(frame: self.view.bounds, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let bookImp = BookImp(context: CoreDataManager.singleCoreDataManager.moc)
        bookImp.excuteQuery(predicateString: nil, limitCount: 10, sortkeys: nil, ascending: true)
        self.view.backgroundColor = UIColor.color(hexString: "#67B0F7")
    }
    
    // MARK: UITableViewDatasource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellReuseIdentifier = "cellReuseIdentifier"
        var cell = tableView .dequeueReusableCell(withIdentifier: cellReuseIdentifier)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellReuseIdentifier)
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var numberOfRows = 0
        if fetchResultsController.sections!.count > 0 {
            let sectionInfo = fetchResultsController.sections![section]
            numberOfRows = sectionInfo.numberOfObjects
        }
        
        return numberOfRows
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

